package com.huangjue.backend.controller;

import com.huangjue.backend.entity.Homework;
import com.huangjue.backend.entity.HomeworkReference;
import com.huangjue.backend.entity.HomeworkFinished;
import com.huangjue.backend.entity.StudentCourse;
import com.huangjue.backend.entity.Submission;
import com.huangjue.backend.service.HomeworkService;
import com.huangjue.backend.service.HomeworkReferenceService;
import com.huangjue.backend.service.HomeworkFinishedService;
import com.huangjue.backend.service.StudentCourseService;
import com.huangjue.backend.service.SubmissionService;
import com.huangjue.backend.service.impl.StudentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 学生作业相关接口
 */
@RestController
@RequestMapping("/homework")
@CrossOrigin(origins = "*")
public class HomeworkController {
    @Autowired
    private HomeworkService homeworkService;
    @Autowired
    private HomeworkReferenceService homeworkReferenceService;
    @Autowired
    private HomeworkFinishedService homeworkFinishedService;
    @Autowired
    private SubmissionService submissionService;
    @Autowired
    private StudentCourseService studentCourseService;

    /**
     * 根据视频ID获取作业及其所有附件
     */
    @GetMapping("/list/{videoId}")
    public ResponseEntity<Map<String, Object>> getHomeworksByVideoId(@PathVariable("videoId") Integer videoId) {
        Map<String, Object> response = new HashMap<>();
        List<Homework> list = homeworkService.getHomeworksByVideoId(videoId);
        // 构造带附件的作业列表
        List<Map<String, Object>> result = new java.util.ArrayList<>();
        for (Homework hw : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("homework", hw);
            List<HomeworkReference> references = homeworkReferenceService.getReferencesByHomeworkId(hw.getHomeworkId());
            map.put("referenceList", references);
            result.add(map);
        }
        response.put("success", true);
        response.put("message", "获取作业列表成功");
        response.put("data", result);
        return ResponseEntity.ok(response);
    }

    /**
     * 标记作业为已完成
     */
    @PostMapping("/mark-finished")
    public ResponseEntity<Map<String, Object>> markHomeworkFinished(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Integer userId = (Integer) request.get("userId");
            Integer homeworkId = (Integer) request.get("homeworkId");
            
            if (userId == null || homeworkId == null) {
                response.put("success", false);
                response.put("message", "参数不完整");
                return ResponseEntity.ok(response);
            }
            
            // 检查是否已经标记为完成
            HomeworkFinished existing = homeworkFinishedService.selectByUserIdAndHomeworkId(userId, homeworkId);
            if (existing != null) {
                response.put("success", true);
                response.put("message", "作业已完成");
                return ResponseEntity.ok(response);
            }
            
            // 创建新的完成记录
            HomeworkFinished homeworkFinished = new HomeworkFinished();
            homeworkFinished.setUserId(userId);
            homeworkFinished.setHomeworkId(homeworkId);
            homeworkFinished.setIsFinished(1);
            homeworkFinished.setFinishTime(LocalDateTime.now());
            
            int result = homeworkFinishedService.insert(homeworkFinished);
            
            response.put("success", result > 0);
            response.put("message", result > 0 ? "作业标记为完成" : "标记失败");
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "服务器错误: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 检查作业是否已完成
     */
    @GetMapping("/check-finished")
    public ResponseEntity<Map<String, Object>> checkHomeworkFinished(
            @RequestParam Integer userId,
            @RequestParam Integer homeworkId) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            HomeworkFinished homeworkFinished = homeworkFinishedService.selectByUserIdAndHomeworkId(userId, homeworkId);
            boolean isFinished = homeworkFinished != null && homeworkFinished.getIsFinished() == 1;
            
            response.put("success", true);
            response.put("finished", isFinished);
            response.put("message", isFinished ? "已完成" : "未完成");
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "服务器错误: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取用户所有已完成的作业
     */
    @GetMapping("/finished-list/{userId}")
    public ResponseEntity<Map<String, Object>> getFinishedHomeworks(@PathVariable("userId") Integer userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 这里需要先获取用户的所有作业ID，然后检查完成状态
            // 暂时返回空列表，后续可以优化
            response.put("success", true);
            response.put("data", new java.util.ArrayList<>());
            response.put("message", "获取完成列表成功");
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "服务器错误: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 学生提交作业（JSON方式，信息存放在body中）
     */
    @PostMapping("/submit")
    public ResponseEntity<Map<String, Object>> submitHomework(@RequestBody Submission submission) {
        Map<String, Object> response = new HashMap<>();
        submission.setSubmissionTime(LocalDateTime.now());
        submission.setGrade(null);
        submission.setFeedback(null);
        return ResponseEntity.ok(response);
    }

    /**
     * 查询自己提交的所有作业
     */
    @GetMapping("/my-submissions/{userId}")
    public ResponseEntity<Map<String, Object>> getMySubmissions(@PathVariable("userId") Integer userId) {
        Map<String, Object> response = new HashMap<>();
        List<Submission> list = submissionService.getSubmissionsByUserId(userId);
        response.put("success", true);
        response.put("message", "获取提交记录成功");
        response.put("data", list);
        return ResponseEntity.ok(response);
    }

    /**
     * 查询自己某个作业的提交记录
     */
    @GetMapping("/my-submission/{homeworkId}/{userId}")
    public ResponseEntity<Map<String, Object>> getMySubmissionByHomework(@PathVariable("homeworkId") Integer homeworkId,
                                                                        @PathVariable("userId") Integer userId) {
        Map<String, Object> response = new HashMap<>();
        Submission submission = submissionService.getSubmissionByHomeworkIdAndUserId(homeworkId, userId);
        response.put("success", submission != null);
        response.put("message", submission != null ? "获取提交记录成功" : "未提交该作业");
        response.put("data", submission);
        return ResponseEntity.ok(response);
    }

    /**
     * 上传作业文件
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadHomeworkFile(@RequestParam("file") MultipartFile file,
                                                                  @RequestParam("userId") Integer userId,
                                                                  @RequestParam("courseId") Integer courseId) {
        Map<String, Object> response = new HashMap<>();
        if (file.isEmpty()) {
            response.put("success", false);
            response.put("message", "文件为空");
            return ResponseEntity.ok(response);
        }
        try {
            // 获取文件原始后缀
            String originalFilename = file.getOriginalFilename();
            String suffix = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            // 用时间戳+随机数防止重名
            String fileName = System.currentTimeMillis() + "_" + (int)(Math.random()*10000) + suffix;

            // 用绝对路径存储
            String uploadDir = System.getProperty("user.dir") + "/uploads/homework/";
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            Path filePath = uploadPath.resolve(fileName);
            file.transferTo(filePath.toFile());

            StudentCourse sc = studentCourseService.getByUserIdAndCourseId(userId, courseId);
            if (sc.getDemoNum()<sc.getDemoUnlock()) {
                sc.setDemoNum(sc.getDemoNum() + 1);
                studentCourseService.update(sc);
            }

            // 返回URL（前端通过 /files/homework/xxx 访问）
            String fileUrl = "/files/homework/" + fileName;
            response.put("success", true);
            response.put("url", fileUrl);
            response.put("message", "上传成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "上传失败: " + e.getMessage());
            return ResponseEntity.ok(response);
        }
    }
} 